package com.qlm.tongji.service.impl;

import java.util.List;

import com.qlm.entity.Admin;
import com.qlm.service.IAuthService;
import com.qlm.view.AdminView;
import com.qlm.view.ResultMessage;

/**
 * 登陆权限管理
 * 
 * @author David
 *
 */
public class AuthServiceImpl implements IAuthService {
	
	private static String T_NAME = "admin";

	@Override
	public AdminView login(AdminView adminView) {
		String name = adminView.getUsername();
		String pwd = adminView.getPassword();
		String sql = "select * from "+T_NAME+" where username = ?  and password =?";
		List<Admin> adminList = Admin.adminDao.find(sql,name,pwd);
		if (adminList.size() == 1) {
			AdminView adv = new AdminView();
			adv.setId(adminList.get(0).getInt("id"));
			adv.setUsername(adminList.get(0).getStr("username"));
			adv.setRoleId(adminList.get(0).getInt("role"));
			adv.setStatus(adminList.get(0).getInt("status"));
			return adv;
		} else {
			return null;
		}
	}

	@Override
	public boolean pwdCheck(String adminName, String pwd) {
		String sql = "select * from "+T_NAME+" where username = '"
				+ adminName + "' and password = '" + pwd + "'";
		List<Admin> admin = Admin.adminDao.find(sql);
		if (admin.size() == 0) {
			return false;
		} else {
			return true;
		}

	}

	@Override
	public ResultMessage adminUpd(AdminView adminView) {
		String sql = "select * from "+T_NAME+" where id = '"
				+ adminView.getId() + "' and password = '" + adminView.getOldPwd() + "'"; 
		List<Admin> admin = Admin.adminDao.find(sql);
		if (admin.size() == 0) {
			return ResultMessage.setAllMessage(ResultMessage.StateDesc.FAIL.getValue(), "原密码输入有误，请重新填写！");
		} else {
			boolean flag = new Admin().findById(adminView.getId()).set("password", adminView.getPassword()).update();
			if(flag){
				return ResultMessage.setAllMessage(ResultMessage.StateDesc.SUCCESS.getValue(), "修改成功！");
			}else{
				return ResultMessage.setAllMessage(ResultMessage.StateDesc.FAIL.getValue(), "修改失败！");
			}
		}
	}

}
